<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>添加学生</title>
  <style>
    .con {
      width: 400px;
      margin: 0 auto;
      padding: 30px;
      border: 1px solid blue;
    }
  </style>
</head>

<body>
  <div class="con">
    <h1>添加学生信息</h1>
    <form action="" method="post">
      <p>
        <label for="class"> 班级：</label>
        <input type="text" name="clazz" id="class" />
      </p>
      <p>
        <label for="name">姓名：</label>
        <input type="text" name="name" id="name" />
      </p>
      <p>
        <label for="gender">性别：</label>
        <input type="radio" name="gender" value="男" checked />男
        <input type="radio" name="gender" value="女" />女
      </p>
      <p>
        <label for="age">年龄：</label>
        <input type="text" name="age" id="age" />
      </p>
      <p>
        <label for="hobby">爱好：</label>
        <input type="checkbox" name="hobby" value="吃饭" /> 吃饭
        <input type="checkbox" name="hobby" value="睡觉" />睡觉
        <input type="checkbox" name="hobby" value="学习" />学习
      </p>
      <p>
        <label for="tel"> 手机号：</label><input type="text" name="tel" id="tel" />
      </p>
      <p>
        <label for="address"> 地址：</label>
        <select name="address" id="">
          <option value="郑州">郑州</option>
          <option value="洛阳">洛阳</option>
          <option value="新乡">新乡</option>
        </select>
      </p>
      <p>
        <label for="remark"> 备注：</label>
        <textarea name="remark" id="remark" cols="30" rows="10"></textarea>
      </p>
      <p>
        <label for="date">入学时间：</label>
        <input type="date" name="date" id="date" />
      </p>
      <p>
        <input type="submit" value="提交" />
      </p>
      <p></p>
    </form>
  </div>
  <script src="./js/utils.js"></script>
  <script>

    var form = document.querySelector('form')
    form.onsubmit = function (e) {
      e.preventDefault();//阻止表单跳转

      // var clazz = document.querySelector('#class').value
      // console.log(clazz);
      // var uname = document.querySelector('#name').value
      // console.log(uname);

      // var data = "clazz=" + clazz + "&name=" + uname;

      var data = serializeKeyValue(this)
      // 1.创建XMLHttpRequest对象
      var xhr = new XMLHttpRequest();
      // 2. 添加状态改变的回调函数,
      xhr.onreadystatechange = function () {
        //5 判断请求状态为4
        if (xhr.readyState == 4) {
          // 6 判断响应状态码
          if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) {
            window.location.href = "index.html"
          }
        }
      }
      // 3. 打开连接设置请求方式和URL
      var url = "http://localhost:3008/api/student/addStudent";

      xhr.open("POST", url)
      xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
      // 4. 发送请求
      xhr.send(data);


    }
  </script>
</body>

</html>